/*
 * @Author: yangzonglong
 * @Date: 2021-03-05 12:08:36
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-30 17:02:59
 * @Auditor:
 */
import React, { useState, useImperativeHandle, forwardRef, useEffect } from 'react';
import { Picker } from 'antd-mobile';
import Icon from './icon/Icon';
import RequiredMark from './RequiredMark';

const divStyle = {
  border: '1px solid rgba(35, 37, 40, 0.1)',
  padding: '12px 14px',
  fontSize: '14px',
  height: ' 45px',
  position: 'relative',
  lineHeight: '19px',
};

const iconStyle = {
  position: 'absolute',
  right: '15px',
  fontSize: '14px',
};

const App = (props, ref) => {
  const { disabled, formItemProps, selectProps } = props;
  const [value, setValue] = useState(undefined);
  const dataSource = props?.selectProps?.dataSource || [];

  useEffect(() => {
    if (props.initialValue) setValue(props.initialValue);
  }, [props.initialValue]);

  useImperativeHandle(ref, () => ({
    getData: () => value,
  }));

  return (
    <Picker data={dataSource} disabled={disabled} cols={1} value={value} onOk={setValue}>
      <div className="am-list-item am-input-item am-list-item-middle">
        <div className="am-list-line">
          <div className="am-input-label am-input-label-5">
            {
              <span>
                {formItemProps?.required && <RequiredMark />}
                {formItemProps?.label}
              </span>
            }
          </div>
          <div style={divStyle}>
            {value ? (
              <>
                {dataSource.filter((item) => item.value === value?.[0] || item.value === value)?.[0]?.label || ''}
                <Icon
                  onClick={(e) => {
                    e.stopPropagation();
                    setValue(undefined);
                  }}
                  icon="&#xe645;"
                  style={{ ...iconStyle, zIndex: 999 }}
                />
              </>
            ) : (
              <>
                <span style={{ color: '#bbb' }}>{selectProps?.placeholder || ''}</span>
                <Icon icon="&#xe669;" style={iconStyle} />
              </>
            )}
          </div>
        </div>
      </div>
    </Picker>
  );
};

export default forwardRef(App);
